import { getToken } from '@/utils/auth'
import { updateClub, getClubDetailByPerm } from '@/api/club'
import RichText from '@/components/richText'
import { getClubType } from '@/api/clubType'
import { getText, isNull } from '@/utils/validate'
import { getFacultyList, getTeacher } from '@/api/school'
import 'babel-polyfill'
import cropUpload from 'vue-image-crop-upload/upload-2.vue'

const defaultForm = {
  name: '',
  type_id: undefined,
  established_time: undefined,
  introduction: '',
  photo: [],
  teacher_id: undefined,
  file: [],
  business_unit_id: undefined,
  image: [],
  rich_text: ''
}

export default {
  // name: 'UpdateNotify',
  components: { RichText, cropUpload },
  data() {
    return {
      loading: false,
      loadingText: '',
      upload_limit: 1,
      richUploadUrl: process.env.VUE_APP_BASE_API + 'api/upload/images/',
      richHeaders: { Authorization: 'Bearer ' + getToken() },
      richMeta: { dir_name: 'notify' },
      elUploadUrl: process.env.VUE_APP_BASE_API + 'api/upload/upload_img/',
      elData: { dir_name: 'create_club' },
      previewDialogVisible: false,
      // fileList: [],
      fileList: { club_images: [] },
      applyFileList: [],
      imageFileList: [],
      searchLoading: false,
      form: JSON.parse(JSON.stringify(defaultForm)),
      facultyList: [],
      teacherList: [],
      teacherInfo: {},
      rules: {
        name: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        type_id: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        business_unit_id: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        teacher_id: [{ required: true, message: '该项为必填项', trigger: 'change' }],
        introduction: [{ required: true, message: '该项为必填项', trigger: 'blur' }],
        file: [{ required: true, message: '必须上传文件', trigger: 'change' }],
        photo: [{ required: true, message: '必须上传文件', trigger: 'change' }],
        image: [{ required: true, message: '必须上传文件', trigger: 'change' }]
      },
      fileLimitCnt: 3, // 申请文件的上传数量
      fileLimitSize: 5, // 申请文件的上传大小
      imageLimitCnt: 3, // 轮播图的上传数量
      imageLimitSize: 5, // 轮播图的上传大小
      imagecropperShow: false,
      imagecropperKey: 0,
      imgDataUrl: '',
      clubTypeList: [],
      previewPicture: false,
      previewurl: ''
    }
  },
  watch: {
  },
  created() {
    this.getClubType()
    this.getFacultyList()
    this.id = this.$route.query.club
    if (this.id) {
      const loading = this.$loading({
        lock: true,
        text: '正在获取数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      getClubDetailByPerm(this.id).then(res => {
        loading.close()
        this.form = res
        this.applyFileList = res.club_files
        this.imageFileList = res.club_images
        this.remoteMethod(res.teacher_realname)
        this.teacherInfo = { username: res.teacher_username, realname: res.teacher_realname, faculty_title: res.teacher_faculty_title }
        this.imgDataUrl = res.club_photo[0].url
      }).catch((error) => {
        this.$message.error(error.response.data.message)
      })
    }
  },
  methods: {
    // 裁剪成功
    cropSuccess(imgDataUrl, field) {
      console.log('-------- crop success --------')
      this.form.photo = []
      this.imgDataUrl = imgDataUrl
    },
    cropUploadSuccess(jsonData, field) {
      console.log('-------- 上传成功 --------')
      console.log(jsonData)
      this.imagecropperShow = false
      this.form.photo.push(jsonData)
      this.$refs.form.validateField('photo')
    },
    cropUploadFail(status, field) {
      console.log('-------- 上传失败 --------')
      console.log(status)
      this.imagecropperShow = false
      this.$message({
        message: '上传文件失败',
        type: 'danger'
      })
    },
    // 裁剪组件，用户选取文件后
    fileSet(fileName, fileType, fileSize) {
      console.log(fileName, fileType, fileSize)
      this.form.photo = []
      const limit = 5 // 限制5M大小
      const flag = fileSize / 1024 / 1024 < limit
      if (!flag) {
        this.imagecropperShow = false
        this.$message.error('上传文件大小不能超过' + limit + 'M')
        return false
      }
    },

    // 获取社团下拉框列表
    getClubType() {
      getClubType({ is_active: true }).then(res => {
        this.clubTypeList = res
      })
    },
    // 获取二级单位下拉框列表
    getFacultyList() {
      getFacultyList().then(res => {
        this.facultyList = res.data
      })
    },
    // 指导老师搜索事件
    remoteMethod(query) {
      if (query !== '') {
        this.searchLoading = true
        const listQuery = { search_key: query }
        setTimeout(() => {
          getTeacher(listQuery).then(res => {
            this.teacherList = res
            this.searchLoading = false
          })
        }, 200)
      } else {
        this.teacherList = []
      }
    },
    teacherChange(val) {
      for (var i = 0; i < this.teacherList.length; i++) {
        if (this.teacherList[i].id === val) {
          this.teacherInfo = this.teacherList[i]
          return true
        }
      }
      this.teacherInfo = {}
    },

    // 获取富文本的纯文本内容，用于表单验证
    getRichText(text) {
      this.form.rich_text = text
    },

    // 获取富文本
    getRichHtml(content) {
      this.form.introduction = content
    },

    // 提交表单
    onSubmit() {
      const textTmp = getText(this.form.introduction)
      if (isNull(textTmp)) {
        this.form.introduction = ''
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在处理',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          updateClub(this.form.id, this.form).then(response => {
            loading.close()
            this.$notify({
              title: '成功',
              message: '提交成功',
              type: 'success',
              duration: 2000
            })
            this.$router.push({
              name: 'MyClub'
            })
          }).catch((error) => {
            loading.close()
            this.$notify({
              title: '失败',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        } else {
          this.$message.error('有必填项没填，或者填写错误，请检查表单。')
        }
      })
    },

    // 上传文件之前的钩子
    beforeUpload(file, typeName, limit = 10) {
      // 限制文件上传大小, 大于1M则提示, 且不请求提交表单
      const flag = file.size / 1024 / 1024 < limit
      if (!flag) {
        this.$message.error('上传文件大小不能超过' + limit + 'M')
        return false
      }
    },
    // 上传文件数量超出自定义数量
    handleExceed(files, fileList) {
      this.$message.warning('已达到最大上传数量, 请删除后继续上传')
    },
    handleProgress(event, file, fileList) {
      this.loading = true
      this.loadingText = '正在上传文件....'
    },
    // 上传成功回调
    handleSuccess(response, typeName) {
      this.loading = false
      this.$message({
        message: '上传文件成功',
        type: 'success'
      })
      if (typeName === 'apply') {
        this.form.file.push(response)
        this.$refs.form.validateField('file')
      } else if (typeName === 'image') {
        this.form.image.push(response)
        this.$refs.form.validateField('image')
      }
    },
    // 上传失败
    handleError(res_error, file, fileList) {
      this.loading = false
      this.$message({
        message: '上传文件失败',
        type: 'danger'
      })
    },
    // 文件列表移除文件
    handleRemove(file, typeName) {
      let key = ''
      if (file.response) {
        key = file.response.data
      } else {
        key = file.url
      }
      if (typeName === 'apply') {
        for (var i = 0; i < this.form.file.length; i++) {
          if (key.match(this.form.file[i].data)) {
            this.form.file.splice(i, 1)
            break
          }
        }
      } else if (typeName === 'image') {
        for (var j = 0; j < this.form.image.length; j++) {
          if (key.match(this.form.image[j].data)) {
            this.form.image.splice(j, 1)
            break
          }
        }
      }
    },

    // 预览图片
    previewImage(file) {
      this.previewPicture = true
      this.previewurl = file.url
      // this.$refs.viewer.$viewer.show()
    },

    previewFile(file) {
      window.open(file.url)
    }

  }
}
